package com.cencus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cencus.domain.Code;
import com.cencus.domain.Record;
import com.cencus.domain.Tag;
import com.cencus.service.RecordService;
import com.cencus.service.impl.RecordServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/records")
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
public class RecordController {
    @Autowired
    private RecordServiceImpl recordService;

    @PostMapping
    public Result createRecord(@RequestBody Record record) {
        Record recordServiceRecord = recordService.createRecord(record);
        return new Result(Code.OK, recordServiceRecord);
    }

    @PutMapping("/{recordId}")
    public Result updateRecord(@PathVariable int recordId, @RequestBody Record record) {
        record.setRecordId(recordId);
        Record updateRecord = recordService.updateRecord(record);
        return new Result(Code.OK, updateRecord);
    }

    @GetMapping
    public Result getAllRecord() {
        return new Result(Code.OK, recordService.getAllRecord());
    }

    @GetMapping("/{recordId}")
    public Result getRecordById(@PathVariable Integer recordId) {
        return new Result(Code.OK, recordService.getRecordById(recordId));
    }
    @GetMapping("/page")
    public Result getRecordById(@RequestParam(defaultValue = "1") long current,
                                @RequestParam(defaultValue = "10") long size) {
        Page<Record> page = new Page<>(current, size);
        QueryWrapper<Record> wrapper = new QueryWrapper<>();
        return new Result(Code.OK, recordService.selectRecordWithTagsPage(page, wrapper));
    }

    @DeleteMapping("/{recordId}")
    public Result deleteRecord(@PathVariable Integer recordId) {
        boolean deleteRecord = recordService.deleteRecord(recordId);
        return new Result(Code.OK, deleteRecord);
    }

    @PutMapping("/associated/{recordId}")
    public Result associated(@PathVariable  Integer recordId, @RequestBody List<Tag> tags){
        return new Result(Code.OK,recordService.associated(recordId,tags));
    }
}
